/**
 * 
 */
package com.yerba.ricecooker.utility;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author mxie
 * 
 */
public class DataSet<KEY, DATA>
{
    private class DataUnit
    {
        private int arrayIndex;
        private DATA dataObj;

        public int getArrayIndex()
        {
            return arrayIndex;
        }

        public void setArrayIndex(int arrayIndex)
        {
            this.arrayIndex = arrayIndex;
        }

        public DATA getDataObj()
        {
            return dataObj;
        }

        public void setDataObj(DATA dataObj)
        {
            this.dataObj = dataObj;
        }
    };

    private HashMap<KEY, DataUnit> dataMap = new HashMap<KEY, DataUnit>();
    private ArrayList<DataUnit> dataArray = new ArrayList<DataUnit>();

    public HashMap<KEY, DataUnit> getDataMap()
    {
        return dataMap;
    }

    public void setDataMap(HashMap<KEY, DataUnit> dataMap)
    {
        this.dataMap = dataMap;
    }

    public ArrayList<DataUnit> getDataArray()
    {
        return dataArray;
    }

    public void setDataArray(ArrayList<DataUnit> dataArray)
    {
        this.dataArray = dataArray;
    }

    public void append(KEY key, DATA dataobj)
    {
        DataUnit unit = new DataUnit();
        unit.setArrayIndex(0);
        unit.setDataObj(dataobj);

        getDataMap().put(key, unit);
        getDataArray().add(unit);

        normalize();
    }

    public void insert(KEY key, DATA dataobj)
    {
        DataUnit unit = new DataUnit();
        unit.setArrayIndex(0);
        unit.setDataObj(dataobj);

        getDataMap().put(key, unit);
        getDataArray().add(0, unit);

        normalize();
    }

    private void normalize()
    {
        int arrayindex = 0;
        for (Iterator<DataUnit> iter = getDataArray().iterator(); iter.hasNext();)
        {
            DataUnit unit = iter.next();
            unit.setArrayIndex(arrayindex++);
        }
    }

    public void clear()
    {
        this.getDataMap().clear();
        this.getDataArray().clear();
    }

    public DATA getData(int index)
    {
        DataUnit dataunit = getDataArray().get(index);
        if (dataunit != null)
        {
            return dataunit.getDataObj();
        }
        
        return null;
    }

    public DATA getData(KEY key)
    {
        DataUnit dataunit = getDataMap().get(key);
        if (dataunit != null)
        {
            return dataunit.getDataObj();
        }
        
        return null;
    }

    public int getDataIndex(KEY key)
    {
        return this.getDataMap().get(key).getArrayIndex();
    }

    public int getSize()
    {
        return this.getDataArray().size();
    }
}
